<?php
require_once IA_ROOT.'/addons/goouc_class/library/JMessage/autoload.php';
use JMessage\JMessage;
use JMessage\IM\ChatRoom;
use JMessage\IM\User;
global $_W,$_GPC;
$config = $this->module['config'];
$aliyunVod = new AliyunVod($config['regionId'],$config['AccessKeyID'],$config['AccessKeySecret']);
$lid = intval($_GPC['lid']);
$op = trim(empty($_GPC['op'])?'list':$_GPC['op']);
$lessonname = pdo_get($this->t_lesson,array('id'=>$lid,'weid'=>$_W['uniacid']));
$grouplist = [
    ['name'=>'不转码','id'=>'c6a69495d412d2e3507c855f1f093d6d'],
    ['name'=>'私有加密转码','id'=>'f2c42f91c0d3859e52a0047943fa4a38'],
    ['name'=>'标准加密','id'=>'76eff5bc54a891fbf33ec1263f5357df'],
];
if($op == 'list'){
    $paixu = empty($_GPC['paixu']) ? 1 : $_GPC['paixu'];
    if ($paixu == 1) {
        $order = " ORDER BY `orders` DESC";
    } elseif ($paixu == 2) {
        $order = " ORDER BY `orders` ASC";
    }
    $sonlist = pdo_fetchall("SELECT * FROM ".tablename($this->t_son)." WHERE lessonid = :lessonid AND weid = :weid ".$order,array(':lessonid'=>$lessonname['id'],':weid'=>$_W['uniacid']));

    foreach ($sonlist as $key => $value) {
        //判断录播视频是否有问题
        if($value['sontype'] == 2){
            try{
                $aliyunVod->getPlayInfo($value['key']);
            }catch(Exception $e){
                pdo_update($this->t_son,array('status'=>2),array('id'=>$value['id']));
                $sonlist[$key]['vstatus'] = 404;
            }
        }
        //改成看完视频的人数
          $sonlist[$key]['studynum'] = pdo_fetchcolumn("select COUNT(*) from ".tablename('goouc_class_stady')." where sonid = :sonid and weid = :weid ",[':sonid'=>$value['id'],':weid'=>$_W['uniacid']]);
    }
    if($_W['isajax']){
        $id = intval($_GPC['id']);
        $info = pdo_fetch("SELECT * FROM ".tablename($this->t_son)." WHERE id = :id",array(':id'=>$id));
        if(empty($info)){
            $message = array('code'=>400,'msg'=>'信息不存在');
            echo json_encode($message);exit;
        }
        try{
            $response = $aliyunVod->getVideoPlayAuth($info['key']);
            $aa = $aliyunVod->getPlayInfo($info['key']);
        }catch(Exception $e){
            echo json_encode($e->getMessage());exit;
        }
        $info['response2'] = $aa->VideoBase->CoverURL;
        $info['playAuth'] = $response->PlayAuth;
        $info['aa'] = $aa;
        echo json_encode($info);exit;
    }
}elseif($op == 'getUploadInfo'){
    try{
        $filename = trim($_GPC['filename']);
        $suffix = substr(strrchr($filename,'.'),1);
        $title = str_replace('.'.$suffix,"" , $filename);
        $response = $aliyunVod->create_upload_video($title,$filename);
    }catch(Exception $e){
        echo json_encode($e->getMessage());exit;
    }
    echo json_encode($response);exit;
}elseif($op == 'post'){
    $sonid = intval($_GPC['id']);
    $info = pdo_fetch(" SELECT * FROM ".tablename($this->t_son)." WHERE id = :id AND weid = :weid",array(':id'=>$sonid,':weid'=>$_W['uniacid']));
    $classin_status = $config['classin_status'];
    if(checksubmit('submit')){
        $data['weid'] = $_W["uniacid"];
        $data['sontype'] = $_GPC['sontype'];
        $data['title'] = trim($_GPC["title"]);
        $data['type'] = intval($_GPC["type"]);
        $data['lessonid'] = intval($_GPC["lessonid"]);
        $data['key'] = trim($_GPC["videoId"]);
        $data['image'] = trim($_GPC["image"]);
        $data['status'] = 2;
        $data['object'] = 1;
        $data['orders'] = intval($_GPC['order']);
        $data['pay_money'] = empty($_GPC['pay_money'])?'0.00':round($_GPC['pay_money'],2);
        $data['xnum'] = intval($_GPC['xnum']);
        $data['cardnum'] = intval($_GPC['cardnum']);
        if($data['sontype'] == 1 || $data['sontype'] == 4){
            if(strtotime($_GPC['starttime']) < time()){
                $data['starttime'] = time();
            }else{
                $data['starttime'] = strtotime($_GPC['starttime']);
            }
            $data['vodtranscodegroupid'] = empty($_GPC['vodtranscodegroupid'])?0:$_GPC['vodtranscodegroupid'];
        }
        if ($this->userid == $_W['uid']) {
            message($this->msg);
        }
        if(empty($data['title'])){
            itoast('请填写完整信息的信息','','error');
        }
        $linfo = pdo_get($this->t_lesson,array('id'=>$data['lessonid']));
        $lessonname = pdo_get($this->t_lesson,array('id'=>$_GPC['lessonid'],'weid'=>$_W['uniacid']));
        $lessonname['is_only'];
        $has_son_num = pdo_fetchall("select * from ".tablename($this->t_son)." where weid = :weid AND lessonid = :lessonid",array(':weid'=>$_W['uniacid'],':lessonid'=>$lessonname['id']));
        if($lessonname['is_only'] == 1 && COUNT($has_son_num) >= 1){
            $res = pdo_update($this->t_son,$data,array('id'=>$has_son_num[0]['id']));
            if($res){
                $arr = array(
                    'weid'=>$_W['uniacid'],
                    'admin_uid'=>$_W['uid'],
                    'admin_username'=>$_W['username'],
                    'log_type'=>3,
                    'function'=>'课程管理->修改章节',
                    'content'=>'修改章节:'.$lessonname['title'].'->'.trim($_GPC["title"])
                );
                $this->addlog($arr);
                message('操作成功',$this->createWebUrl('son',array('lid'=>$data['lessonid'])),'succss');
            }else{
                message('操作失败',$this->createWebUrl('son',array('lid'=>$data['lessonid'])),'error');
            }
        }else{
            if(empty($sonid) ){
                $data['updatestatus'] = 1;
                $res = pdo_insert($this->t_son,$data);
                $sonid = pdo_insertid();
                if($res){
                    //如果是直播或者伪直播创建聊天室
                    if($data['sontype'] == 1 || $data['sontype'] == 4){
                        if($config['jmkey'] && $config['jmsecret']){
                            //判断聊天室存在不
                            $checkroom = pdo_get('goouc_class_jg_room',array('sonid'=>$sonid,'weid'=>$_W['uniacid']),array('id'));
                            if(empty($checkroom['id'])){
                                $appkey = $config['jmkey'];
                                $appsecret = $config['jmsecret'];
                                $client = new JMessage($appkey, $appsecret);
                                $room = new ChatRoom($client);
                                $user = new User($client);
                                //先创建拥有者admin,判断拥有者是否存在(一个机构只有一个聊天室拥有者)
                                $info = $user->show('admin');
                                if($info['http_code'] == 403){
                                    $username =  'admin';
                                    $password = '123456';
                                    $response = $user->register($username, $password);
                                }
                                $roomres=$room->create("chartroom".$sonid, 'admin', [], "");
                                $roomdata = [
                                    'weid'=>$_W['uniacid'],
                                    'sonid'=>$sonid,
                                    'roomid'=>$roomres['body']['chatroom_id'],
                                    'ctime'=>time()
                                ];
                                pdo_insert('goouc_class_jg_room',$roomdata);
                            }
                        }

                    }
                    if($config['classin_status'] == 1){
                        $timeStamp=time();
                        $courseId=$_GPC["cl_courseid"];
                        $classId = $_GPC["cl_classid"];
                        $classJson=[
                            [
                                'classId'=>$classId,
                                'record'=>1,
                                'replay'=>1,
                                'live'=>1,
                            ]
                        ];
                        $safeKey=md5($config['SECRET'].$timeStamp);
                        $fields = "SID=".$config['SID']."&safeKey=".$safeKey."&timeStamp=".$timeStamp."&courseId=".$courseId."&classJson=".json_encode($classJson);
                        $action="https://www.eeo.cn/partner/api/course.api.php?action=setClassVideoMultiple";
                        $rep = $this->get_http_array($action,$fields);
                        $rep = json_decode($rep,true);
                        $rtmp = $rep['data'][0]['more_data']['live_info']['RTMP'];
                        $broadurls = [];
                        $broadurls['rtmpurl']= $rtmp;
                        //保存
                        pdo_update('goouc_class_son',array('live_url'=>serialize($broadurls),'cl_courseid'=>$courseId,'cl_classid'=>$classId),array('id'=>pdo_insertid()));
                    }

                    $arr = array(
                        'weid'=>$_W['uniacid'],
                        'admin_uid'=>$_W['uid'],
                        'admin_username'=>$_W['username'],
                        'log_type'=>1,
                        'function'=>'课程管理->新增章节',
                        'content'=>'新增章节:'.$lessonname['title'].'->'.trim($_GPC["title"])
                    );
                    $this->addlog($arr);
                    message('操作成功',$this->createWebUrl('son',array('lid'=>$data['lessonid'])),'succss');
                }else{
                    message('操作失败',$this->createWebUrl('son',array('lid'=>$data['lessonid'])),'error');
                }
            }else{
                if($info['key'] != $_GPC['videoId']){
                    $data['updatestatus'] = 1;
                }
                $res = pdo_update($this->t_son,$data,array('id'=>$sonid));
                if($res){
                    $arr = array(
                        'weid'=>$_W['uniacid'],
                        'admin_uid'=>$_W['uid'],
                        'admin_username'=>$_W['username'],
                        'log_type'=>3,
                        'function'=>'课程管理->修改章节',
                        'content'=>'修改章节:'.$lessonname['title'].'->'.trim($_GPC["title"])
                    );
                    $this->addlog($arr);
                    message('操作成功',$this->createWebUrl('son',array('lid'=>$data['lessonid'])),'succss');
                }else{
                    message('操作失败',$this->createWebUrl('son',array('lid'=>$data['lessonid'])),'error');
                }
            }
        }

    }
}elseif($op == 'delete'){
    if ($this->userid == $_W['uid']) {
        message($this->msg);
    }
    $id = intval($_GPC['id']);
    $info = pdo_fetch("SELECT * FROM ".tablename($this->t_son)." WHERE id = :id",array(':id'=>$id));
    if(empty($info)){
        message('章节信息不存在','','error');
    }
    $title = pdo_get($this->t_son,array('id' => $id),array('title'));
    $res = pdo_delete($this->t_son,array('id'=>$id));
    if($res){
        if(!empty($info['key'])){
            $aliyunVod->delete_videos($info['key']);
        }
        $arr = array(
            'weid'=>$_W['uniacid'],
            'admin_uid'=>$_W['uid'],
            'admin_username'=>$_W['username'],
            'log_type'=>2,
            'function'=>'课程管理->删除章节',
            'content'=>'删除章节:'.$lessonname['title'].'->'.$title['title']
        );
        $this->addlog($arr);
        message('操作成功',$this->createWebUrl('son',array('lid'=>$info['lessonid'])),'succss');
    }else{
        message('操作失败',$this->createWebUrl('son',array('lid'=>$info['lessonid'])),'error');
    }
}elseif($op == 'order'){
    if($_W['isajax']){
        if ($this->userid == $_W['uid']) {
            $message = array('success'=>401,'mess'=>$this->msg);
            echo json_encode($message);exit;
        }
        $id = intval($_GPC['id']);
        $data['orders'] = intval($_GPC['order']);
        $res = pdo_update($this->t_son,$data,array('id'=>$id,'weid'=>$_W['uniacid']));
        if($res){
            $message = array('success'=>1,'mess'=>'状态更改成功');
        }else{
            $message = array('success'=>2,'mess'=>'状态更改失败');
        }
        echo json_encode($message);exit;
    }
}elseif($op == 'changevedio'){
    if($_W['isajax']){
        if ($this->userid == $_W['uid']) {
            $message = array('success'=>401,'mess'=>$this->msg);
            echo json_encode($message);exit;
        }
        $key = $_GPC['key'];
        $sonid = $_GPC['sonid'];
        try {
            $res = $aliyunVod->delete_videos($key);
        } catch (Exception $e) {
            pdo_update($this->t_son,array('key'=>'','vediotime'=>'0.00','status'=>0),array('id'=>$sonid));
            $message = array('success'=>404,'mess'=>$e->getMessage());
            echo json_encode($message);exit;
        }
        if($res){
            try {
                pdo_update($this->t_son,array('key'=>'','vediotime'=>'0.00','status'=>0),array('id'=>$sonid));
                echo json_encode(array('success'=>1,'mess'=>'数据库删除key值成功'));exit;
            } catch (Exception $e) {
                echo json_encode(array('success'=>401,'mess'=>'数据库删除key失败'));exit;
            }
        }
    }
}elseif($op == 'card'){
    if($_W['isajax']){
        if ($this->userid == $_W['uid']) {
            $message = array('success'=>401,'mess'=>$this->msg);
            echo json_encode($message);exit;
        }
        $id = intval($_GPC['id']);
        $data['cardnum'] = intval($_GPC['cardnum']);
        $res = pdo_update($this->t_son,$data,array('id'=>$id,'weid'=>$_W['uniacid']));
        if($res){
            $message = array('success'=>1,'mess'=>'状态更改成功');
        }else{
            $message = array('success'=>2,'mess'=>'状态更改失败');
        }
        echo json_encode($message);exit;
    }
}elseif($op == 'changestatus'){
    if($_W['isajax']){
        $id = intval($_GPC['id']);
        $status = trim($_GPC['status']);
        if($status == '上架'){
            $data['status'] = 2;
        }elseif($status == '下架'){
            $data['status'] = 1;
            //检测视频是否有效 将视频时长等信息添加到课程表
            $soninfo = pdo_get($this->t_son,array('id'=>$id));
            if($soninfo['sontype'] == 2 || $soninfo['sontype'] == 4){
                try{
                    $aa = $aliyunVod->getPlayInfo($soninfo['key']);
                }catch (Exception $e){
                    $message = array('success'=>0,'mess'=>'无效视频，禁止上架');
                    echo json_encode($message);exit;
                }
                if($soninfo['vediotime'] == '0.00'){
                    $data['vediotime'] = $aa->PlayInfoList->PlayInfo[0]->Duration;
                }
            }
        }
        $res = pdo_update($this->t_son,$data,array('id'=>$id,'weid'=>$_W['uniacid']));
        if($res){
            $message = array('success'=>1,'mess'=>'状态更改成功');
        }else{
            $message = array('success'=>2,'mess'=>'状态更改失败');
        }
        echo json_encode($message);exit;
    }
}elseif($op == 'test'){
    $vid = $_GPC['id'];
    try {
        $result = $aliyunVod->submitTranscodeJobs($vid,'1fa7c38a627c45a4b3d516d74e63779f');
    } catch (Exception $e) {
        print $e->getMessage()."\n";
    }
}elseif($op == 'gettransgroupid'){
    /*$list = [
        ['name'=>'不转码','id'=>'c6a69495d412d2e3507c855f1f093d6d'],
        ['name'=>'私有加密转码','id'=>'f2c42f91c0d3859e52a0047943fa4a38'],
        ['name'=>'标准加密','id'=>'76eff5bc54a891fbf33ec1263f5357df'],
    ];
    echo json_encode($list);exit;*/
    try{
        $list = $aliyunVod->templategrouplist();
        var_dump($list);
    }catch(Exception $e){
        $message = ['error'=>$e->getMessage()];
        var_dump($message);
    }
    die();
}elseif($op == 'geturl'){
    $sonid = $_GPC['id'];
    $soninfo = pdo_get($this->t_son,['id'=>$sonid]);
    $lessoninfo = pdo_get($this->t_lesson,['id'=>$soninfo['lessonid']]);
    $liveurl = $config['live_url'];
    $broadurl = $config['broad_url'];


    //获取推流地址中的配置信息  主要获取鉴权key值
    $live_url = $aliyunVod->getlivedomainconfigs($liveurl,'aliauth');
    //获取拉流地址中的配置信息  主要获取鉴权key值
    $broad_url = $aliyunVod->getlivedomainconfigs($broadurl,'aliauth');
    $live_url = json_decode($live_url,true);
    $broad_url = json_decode($broad_url,true);

    //遍历取值
    foreach ($live_url['DomainConfigs']['DomainConfig'][0]['FunctionArgs']['FunctionArg'] as $k => $v) {
        if ($v['ArgName'] == 'auth_key1') {
            $live_key = $v['ArgValue'];//推流主key
        } elseif ($v['ArgName'] == 'ali_auth_delta') {
            $live_time = $v['ArgValue'];//有效期
        }
    }
    foreach ($broad_url['DomainConfigs']['DomainConfig'][0]['FunctionArgs']['FunctionArg'] as $k => $v) {
        if ($v['ArgName'] == 'auth_key1') {
            $broad_key = $v['ArgValue'];//播流主key
        } elseif ($v['ArgName'] == 'ali_auth_delta') {
            $broad_time = $v['ArgValue'];//有效期
        }
    }
    //有效期
    $reTime = $live_time;
    $live_time = time() + $live_time;
    $broad_time = time() + $broad_time;

    //设置appname 以及streamname
    $appname = $config['appname'];
    $streamname = $soninfo['id'].date("ymd");
    //生成推送地址
    $strpush = '/'.$appname.'/'.$streamname.'-'.$live_time.'-0-0-'.$live_key;
    $liveurls_url = 'rtmp://'.$liveurl.'/'.$appname.'/';
    $liveurls_token = $streamname.'?auth_key='.$live_time.'-0-0-'.md5($strpush);
    //生成观看地址

    $strviewrtmp = '/'.$appname.'/'.$streamname.'-'.$broad_time.'-0-0-'.$broad_key;
    $strviewflv = '/'.$appname.'/'.$streamname.'.flv-'.$broad_time.'-0-0-'.$broad_key;
    $strviewm3u8 = '/'.$appname.'/'.$streamname.'.m3u8-'.$broad_time.'-0-0-'.$broad_key;
    //'rtmp://broad.9lan.cn/2019-09-18/test?auth_key=1568799597-0-0-4b4a3910884a66160623274a060ed4d8';
    $broadurls = [];
    $broadurls['rtmpurl']= 'rtmp://'.$broadurl.'/'.$appname.'/'.$streamname.'?auth_key='.$broad_time.'-0-0-'.md5($strviewrtmp);
    $broadurls['flvurl']= 'http://'.$broadurl.'/'.$appname.'/'.$streamname.'.flv?auth_key='.$broad_time.'-0-0-'.md5($strviewflv);
    $broadurls['m3u8url']= 'http://'.$broadurl.'/'.$appname.'/'.$streamname.'.m3u8?auth_key='.$broad_time.'-0-0-'.md5($strviewm3u8);
    $datass = ['live_url'=>$liveurls_url,'live_url_token'=>$liveurls_token,'broad_url'=>$broadurls];
    //将数据拼接 存数据库
    $url_time = ['live_url_time'=>$live_time,'broad_url_time'=>$broad_time];
    $data = [
        'live_url'=>$liveurls_url.$liveurls_token,
        'broad_url'=>serialize($broadurls),
        'create_url_time'=>time(),
        'url_time'=>serialize($url_time)
    ];
    pdo_update($this->t_son,$data,['id'=>$soninfo['id']]);
   // pdo_debug();
    //直播记录表里若没数据就插入
    $conData = [
        'sonid' => $sonid,
        'stream' => $streamname,
        'app' => $appname,
        'weid' => $_W['uniacid'],
    ];
    $checkRecord = pdo_get('goouc_class_live_record',array('sonid'=>$sonid,'stream'=>$streamname,'app'=>$appname,'weid'=>$_W['uniacid']),array('id'));
    if (!$checkRecord) {
        $conData['ctime'] = time();
        pdo_insert('goouc_class_live_record',$conData);
    }
    echo json_encode($datass);exit;
}elseif($op == 'download'){
    $sonid = $_GPC['sonid'];
    $soninfo = pdo_get($this->t_son,['id'=>$sonid]);
    //学习人数
    $usergroup = pdo_fetchall("select ust.uid,u.nickname,u.phone from ".tablename('goouc_class_user_son_time')." ust JOIN ".tablename($this->t_user)." u ON ust.uid = u.id where ust.weid = :weid and ust.sonid = :sonid group by uid",[':weid'=>$_W['uniacid'],':sonid'=>$sonid]);
    foreach($usergroup as $k => $v){
        $time = pdo_fetchcolumn("select SUM(`time`) from ".tablename('goouc_class_user_son_time')." where uid = :uid and sonid = :sonid",[':uid'=>$v['uid'],':sonid'=>$sonid]);
        $usergroup[$k]['looktime'] = ceil($time/60);
    }
    //var_dump($usergroup);die();
    //制作表格
    $name = $soninfo['title'];
    $objPHPExcel = new PHPExcel;
    $objPHPExcel->getProperties()->setCreator("zxf")->setLastModifiedBy("zxf")->setTitle('数据EXCEL导出')->setSubject('数据EXCEL导出')->setDescription('导出数据')->setKeywords("excel")->setCategory("result file");
    $objPHPExcel->setActiveSheetIndex(0);

    $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);//行高

    $objPHPExcel->getActiveSheet()->getStyle('1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objPHPExcel->getActiveSheet()->getStyle('1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
    $objPHPExcel->getActiveSheet()->getStyle('1')->getFont()->setSize(14);     //字体大小
    $objPHPExcel->getActiveSheet()->getStyle('1')->getFont()->setBold(true);      //第一行是否加粗

    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);//列宽
    $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);//列宽
    $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);//列宽

    $objPHPExcel->getActiveSheet()->setCellValue('A1', '学习者');
    $objPHPExcel->getActiveSheet()->setCellValue('B1', '手机号');
    $objPHPExcel->getActiveSheet()->setCellValue('C1', '观看总时长');
    $key = 2;
    foreach($usergroup as $k=>$v){
        $objPHPExcel->getActiveSheet()->setCellValue('A'.$key, $v['nickname']);
        $objPHPExcel->getActiveSheet()->setCellValue('B'.$key, $v['phone']);
        $objPHPExcel->getActiveSheet()->setCellValue('C'.$key, $v['looktime'].'分钟');
        $key++;
    }
    ob_end_clean();
    header('Content-Type: application/vnd.ms-excel'); //文件类型
    header('Content-Disposition: attachment;filename="'.$name.'.xls"'); //文件名
    header('Cache-Control: max-age=0');
    header('Content-Type: text/html; charset=utf-8'); //编码
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel 2003
    $objWriter->save('php://output');
    exit;
}
include $this->template('web/son');
?>

